package com.ck.controller.admin;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Teacher;
import com.ck.service.AdminService;

public class EditTeacherInfoController extends SimpleFormController {

	private AdminService adminService;

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Integer teacherID = Integer.parseInt(request.getParameter("teacherID"));
		Teacher teacher = adminService.gainTeacher(teacherID);
		return teacher;
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		Integer teacherID = Integer.parseInt(request.getParameter("teacherID"));
		Teacher teacher = (Teacher) command;
		teacher.setId(teacherID);

		Map model = errors.getModel();
		
		//后台校验
        boolean flag = true;
        String truename = teacher.getTruename().trim();
        String email = teacher.getEmail().trim();
        
        if(truename == null || "".equals(truename)) {
			model.put("error_truename", "请输入真实姓名");
			flag = false;
		}
		
		if(truename.length() > 12) {
			model.put("error_truename", "真实姓名长度：1-12个字符");
			flag = false;
		}
        
        if( email == null || "".equals(email) ){
        	teacher.setEmail(null);
        }else{
	        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
			Matcher m = p.matcher(email);
			if(!m.matches()){
				model.put("error_email", "email格式不正确");
				flag = false;
			}
        }
		
		if(email.length() > 40){
			model.put("error_email", "email长度：0-40个字符");
			flag = false;
		}
        
		//校验不通过
		if(!flag){
			return new ModelAndView(getFormView(), model);
		}

		boolean isEditTeacherInfo = adminService.editTeacherInfo(teacher);

		if (isEditTeacherInfo) {
			return new ModelAndView(getSuccessView());
		} else {
			return new ModelAndView(getFormView(), model);
		}
	}
}
